#include "rtc_app.h"
#include "timestamp.h"
#include "aip8563_app.h"
#include "real_time_app.h"
#include "real_time_board.h"

bool RealTimeTimestampToRtc(uint32_t Timestamp)
{
  if ((Timestamp != 0x00000000) && (Timestamp != 0xFFFFFFFF))
  {
    TimeFormat_t DeviceRealTime = {0};
    TimestampToNormalTime(Timestamp, false, &DeviceRealTime);

#if (_REAL_TIME_CLOCK_SOURCE_ == _EXTERNAL_CLOCK_SOURCE_)
    Aip8563SetRealTimeTime(&DeviceRealTime);
    printf("DeviceRealTime %08x set time success\r\n",Timestamp);
#else
    RtcUpdateDeviceTime(Timestamp);
#endif

    return true;
  }

  return false;
}

uint32_t RealTimeMakeCurrentTimestamp(void)
{
  uint8_t TimeZone = 0;
  uint32_t Timestamp = 0;
  TimeFormat_t RealTimeTime = {0};

#if (_REAL_TIME_CLOCK_SOURCE_ == _EXTERNAL_CLOCK_SOURCE_)
  Aip8563GetRealTimeTime(&RealTimeTime);
#else
  RtcGetDeviceTime(&RealTimeTime);
#endif
  Timestamp = MakeTimestamp(&RealTimeTime);
  printf("get real time %08x \r\n",Timestamp);
  if (Timestamp > INITIALIZATION_SYSTEM_TIME)
  {
    TimeZone = GetDeviceTimeZone();
    printf("get TimeZone %08x \r\n",TimeZone);
    if (((TimeZone >= 0) && (TimeZone <= 11)) || ((TimeZone <= 0xFF) && (TimeZone >= 0xF5)))
    {
      if (TimeZone & 0xF0)
      {
        Timestamp -= ((0xFF - TimeZone) + 1) * 60 * 60;
      }
      else
      {
        Timestamp += (TimeZone * 60 * 60);
      }

      return Timestamp;
    }
  }

  return INITIALIZATION_SYSTEM_TIME;
}

void RealTimeRtcGetCurrentTime(uint16_t *pYr, uint8_t *pMt, uint8_t *pDe, uint8_t *pHr, uint8_t *pMe, uint8_t *pSd, uint8_t *pWk)
{
  uint32_t NowTimestamp = 0;
  TimeFormat_t RealTimeTime = {0};

  NowTimestamp = RealTimeMakeCurrentTimestamp();
  NowTimestamp += 8 * 60 * 60;
  TimestampToNormalTime(NowTimestamp, false, &RealTimeTime);

  if (pYr != NULL)
  {
    *pYr = (uint16_t)RealTimeTime.Year;
  }

  if (pMt != NULL)
  {
    *pMt = (uint8_t)RealTimeTime.Month;
  }

  if (pDe != NULL)
  {
    *pDe = (uint8_t)RealTimeTime.Date;
  }

  if (pHr != NULL)
  {
    *pHr = (uint8_t)RealTimeTime.Hour;
  }

  if (pMe != NULL)
  {
    *pMe = (uint8_t)RealTimeTime.Minute;
  }

  if (pSd != NULL)
  {
    *pSd = (uint8_t)RealTimeTime.Second;
  }

  if (pWk != NULL)
  {
    *pWk = (uint8_t)RealTimeTime.Week;
  }
}

void RealTimeInitialization(void)
{
  uint32_t NowTimestamp = RealTimeMakeCurrentTimestamp();
  uint32_t LastActionTimestamp = GetSystemLastActionTime();

  PRINT("[time]: now time: %d, last action time: %d\r\n", NowTimestamp, LastActionTimestamp);
  if (abs((int)(NowTimestamp - LastActionTimestamp)) > ERROR_TIME)
  {
    RealTimeTimestampToRtc(LastActionTimestamp);
  }
}

void RealTimeConfiguration(void)
{
#if (_REAL_TIME_CLOCK_SOURCE_ == _EXTERNAL_CLOCK_SOURCE_)
  Aip8563Configuration();
#endif
}
